package com.cuit.zuke.system.controller;

import com.cuit.zuke.common.util.Constant;
import com.cuit.zuke.common.util.PageUtil;
import com.cuit.zuke.common.util.Result;
import com.cuit.zuke.system.entity.SysRoleEntity;
import com.cuit.zuke.system.service.SysRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: zuke
 * @description: 角色管理
 * @author: KamTang
 * @create: 2022-04-26 20:46
 **/
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends SysAdminAbstractController {

    @Autowired
    private SysRoleService roleService;

    @GetMapping("/list")
    public Result getRoleList (@RequestParam Map<String, Object> params) {
        //如果不是超级管理员，则只查询自己创建的角色列表
        if(getAdmin().getUserId() != Constant.SUPER_ADMIN){
            params.put("createUserId", getAdmin().getUserId());
        }
        PageUtil page = roleService.queryPage(params);
        return Result.ok().put("page", page);
    }

    @GetMapping("/select")
    public Result select () {
        Map<String, Object> map = new HashMap<>(16);
        // 如果不是超级管理员，则只查询自己所拥有的角色列表
        if(getAdmin().getUserId() != Constant.SUPER_ADMIN){
            map.put("create_user_id", getAdmin().getUserId());
        }
        List<SysRoleEntity> list = roleService.listByMap(map);
        return Result.ok().put("list", list);
    }

    @PostMapping("/save")
    @RequiresPermissions("sys:role:save")
    public Result saveRole (@RequestBody SysRoleEntity role) {
        role.setCreateUserId(getAdmin().getUserId());
        roleService.saveRole(role);
        return Result.ok();
    }

    @PostMapping("/update")
    @RequiresPermissions("sys:role:update")
    public Result update (@RequestBody SysRoleEntity role) {
        role.setCreateUserId(getAdmin().getUserId());
        roleService.update(role);
        return Result.ok();
    }

    /**
     * 批量删除角色
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    @RequiresPermissions("sys:role:delete")
    public Result deleteBatch (@RequestBody Long[] ids){
        roleService.deleteBatch(ids);
        return Result.ok();
    }

    /**
     * 根据角色id获取角色具体信息
     * @param roleId
     * @return
     */
    @GetMapping("/info/{roleId}")
    public Result info(@PathVariable("roleId") Long roleId) {
        return Result.ok().put("roleInfo", roleService.getRoleInfoById(roleId));
    }

    @GetMapping("/select/{userId}")
    public Result getRoleByUserId(@PathVariable("userId") Long userId) {
        return Result.ok().put("role", roleService.getRoleInfoByUserId(userId));
    }
}
